import Component from "../Component.js";
import { SensorTypeU } from "../../experience/drawer/SensorType.js";
import Type from "../../experience/db/Type.js";

const Feature = ol.Feature;
const Polygon = ol.geom.Polygon;
const Point = ol.geom.Point;
const Text = ol.style.Text;
const Fill = ol.style.Fill;
const Stroke = ol.style.Stroke;
const Style = ol.style.Style;
const CircleStyle = ol.style.Circle;
export default class Message extends Component {
    constructor() {
        super();
        this.featureId = ''
        this.pointsFeature = []
    }

    async createSensor(data, e) {
        this.emitter.emit("open-sensor-move");
        await this.drawer.draw(Type.Sensor);
        this.drawer.map.getView().setZoom(9);
        const center = this.drawer.map.getView().getCenter();
        const sensor = { sensorType: data.sensorType, sensorStatus: data.sensorStatus };

        const x = this.algo.denormalX(center[0]);
        const y = this.algo.denormalY(center[1]);

        const feature = new Feature();
        const text = new Text({
            text: SensorTypeU[sensor.sensorType],
            fill: new Fill({ color: "blue" }),
            font: `normal 40px "iconfont"`
        });
        feature.set("type", Type.Sensor);
        feature.setStyle(new Style({ text: text }));
        feature.setGeometry(new Point(center));
        this.drawer.source(Type.Modify).addFeature(feature);

        const json = { x: x, y: y, z: 0, from: "tank", type: "newPoint" };
        e.source.postMessage(JSON.stringify(json), "*");
    }

    async selectSensor(data, e) {
        this.emitter.emit("open-sensor-move");
        await this.drawer.draw(Type.Sensor);
        this.drawer.map.getView().setZoom(9);

        const sourceX = data.pointList[0].x;
        const sourceY = data.pointList[0].y;
        const x = this.algo.normalX(sourceX);
        const y = this.algo.normalY(sourceY);

        const feature = new Feature();
        const text = new Text({
            text: SensorTypeU[data.sensorType],
            fill: new Fill({ color: "blue" }),
            font: `normal 40px "iconfont"`
        });
        feature.set("type", Type.Sensor);
        feature.setStyle(new Style({ text: text }));
        feature.setGeometry(new Point([x, y]));
        this.drawer.source(Type.Modify).clear();
        this.drawer.source(Type.Modify).addFeature(feature);
        this.drawer.map.getView().setCenter([x, y]);

        const json = { x: sourceX, y: sourceY, z: 0, from: "tank", type: data.clickType };
        e.source.postMessage(JSON.stringify(json), "*");
    }

    async copySensor(data, e) {
        this.emitter.emit("open-sensor-move");
        await this.drawer.draw(Type.Sensor);

        const center = this.drawer.map.getView().getCenter();
        this.drawer.map.getView().setZoom(9);
        const sensor = { sensorType: data.sensorType, sensorStatus: data.sensorStatus };

        center[0] = center[0] + 5;
        const x = this.algo.denormalX(center[0]);
        const y = this.algo.denormalY(center[1]);

        const feature = new Feature();
        const text = new Text({
            text: SensorTypeU[sensor.sensorType],
            fill: new Fill({ color: "blue" }),
            font: `normal 40px "iconfont"`
        });
        feature.set("type", Type.Sensor);
        feature.setStyle(new Style({ text: text }));
        feature.setGeometry(new Point(center));
        this.drawer.source(Type.Modify).addFeature(feature);

        const json = { x: x, y: y, z: 0, from: "tank", type: "copyPoint" };
        e.source.postMessage(JSON.stringify(json), "*");
    }

    async modifySensor(data, e) {
        await this.drawer.draw(Type.Sensor);
        const feature = this.drawer.source(Type.Sensor).getFeatureById(data.id);
        const sensorType = feature.get("sensorType");
        const text = new Text({
            text: SensorTypeU[sensorType],
            fill: new Fill({ color: "blue" }),
            font: `normal 40px "iconfont"`
        });
        feature.setStyle(new Style({ text: text }));
        this.emitter.emit("open-sensor-move");
    }
    async rootPointSensor(data, e) {
        this.utils.setLocalStorage("rootSensor", data.id);
        this.emitter.emit("root-sensor-move")
    }
    //断层
    async faultageSensor(data, e) {
        const feature = this.drawer.source(Type.Fault).getFeatureById(data.res.id);
        if (feature) {
            const point = feature.getGeometry().getCoordinates();
            this.drawer.map.getView().setCenter(point[0][0]);
            this.drawer.map.getView().setZoom(10);
        }

    }

    async newFaultage(data, e) {
        this.emitter.emit("faultage-sensor-move")
    }

    async refreshFault(data, e) {
        const config = this.algo.getConfig();
        if (config == null) return;
        const data2 = await this.api.getFaultList(config.mine_code);
        if (data2.data === null) {
            return;
        }
        await this.db.refresh(Type.Fault, data2.data);
        await this.drawer.draw(Type.Fault);
    }

    // 裂隙带
    async fracturezoneSensor(data, e) {
        const feature = this.drawer.source(Type.Fissure).getFeatureById(data.res.id);
        if (feature) {
            const point = feature.getGeometry().getCoordinates();
            // this.drawer.map.getView().setCenter(point[0]);
            // this.drawer.map.getView().setZoom(10);
            this.drawer.map.getView().animate({ // 只设置需要的属性即可
                center: point[0], // 中心点
                duration: 1000, // 缩放持续时间，
                zoom: 11
            })

        }

    }

    async newFracturezone(data, e) {
        this.emitter.emit("fissure-sensor-move")
    }

    async refreshFracturezone(data, e) {
        const config = this.algo.getConfig();
        if (config == null) return;
        const data2 = await this.api.getFissures(config.mine_code);
        if (data2.data === null) {
            return;
        }
        await this.db.refresh(Type.Fissure, data2.data);
        await this.drawer.draw(Type.Fissure);
    }

    // 富水区
    async waterenrichedareaSensor(data, e) {
        const feature = this.drawer.source(Type.Water).getFeatureById(data.res.id);
        if (feature) {
            const point = feature.getGeometry().getCoordinates();
            // this.drawer.map.getView().setCenter(point[0]);
            // this.drawer.map.getView().setZoom(10);
            var polygon = turf.polygon(point);
            var centroid = turf.centroid(polygon);
            this.drawer.map.getView().animate({ // 只设置需要的属性即可
                center: centroid.geometry.coordinates, // 中心点
                duration: 1000, // 缩放持续时间，
                zoom: 12
            })

        }

    }

    async newWaterenrichedarea(data, e) {
        this.emitter.emit("water-sensor-move")
    }

    async refreshWaterenrichedarea(data, e) {
        const config = this.algo.getConfig();
        if (config == null) return;
        const data2 = await this.api.getWaters(config.mine_code);
        if (data2.data === null) {
            return;
        }
        await this.db.refresh(Type.Water, data2.data);
        await this.drawer.draw(Type.Water);
    }

    // 控制双屏显隐
    async doubleScreen(data, e) {
        // this.$$('#map2').css('display', data.isShow ? 'block' : 'none')
        if(data.type === 'showScreen') { // 双屏显示
            this.$$('#map2').css('display', 'block')
            this.drawer.init2();
        }
        if(data.type === 'hiddenScreen') { // 双屏隐藏
            this.$$('#map2').css('display', 'none')
        }
    }

    // 添加微震点
    async addLayer(data, e) {
        if (data.type === 'slightPoint') {
            this.$$(`#pointS`).remove()
            if ( this.pointsFeature.length !== 0) {
                this.pointsFeature.forEach((item) => {
                    this.drawer.source(Type.SlightPoint).removeFeature(item);
                })
                this.pointsFeature = []
            }
            data.data.forEach((item) => {
            const feature = new Feature({
                geometry: new Point([this.algo.normalX(item.x), this.algo.normalY(item.y)]),
                programs: item,
            })
            feature.setStyle(new Style({
                image: new CircleStyle({
                    radius: item.size,
                    // radius: 50,
                    fill: new Fill({
                        color: item.color
                    })
                })
            }));
            feature.set('type', Type.SlightPoint);
            feature.setId(item.x);
            this.pointsFeature.push(feature)
            })
            this.drawer.source(Type.SlightPoint).addFeatures(this.pointsFeature);
            const x = this.algo.normalX(data.center[0]);
            const y = this.algo.normalY(data.center[1]);
            
            this.drawer.map.getView().animate({ // 只设置需要的属性即可
                center: [x, y], // 中心点
                duration: 1000, // 缩放持续时间，
                zoom: 11
            })
    
            const json = { x: x, y: y, z: 0, from: "tank", type: "slightPoint" };
            e.source.postMessage(JSON.stringify(json), "*");
        } else if(data.type === 'slightKriging') {
            this.drawer.fotKrigingLayer(data)
        }
       
    }

    // 删除微震点
    async removeLayer(data, e) { }

    async rootPolygonSensor(data, e) {
        const feature = new Feature();
        feature.setId(data.id);
        feature.set('type', Type.RootPolygon);
        const polygonColor = data.polygonColor
        const polylineColor = data.polylineColor
        const style = new Style({
            stroke: new Stroke({
                color: polylineColor, //面的边界线颜色
                width: 1         //边界线宽
            }),
            fill: new Fill({
                color: polygonColor    //填充颜色，不透明度0
            })
        })
        feature.setStyle(style);
        const positions = data.positions
        for (const coor of positions) {
            coor[0] = this.algo.normalX(coor[0]);
            coor[1] = this.algo.normalY(coor[1]);
        }
        feature.setGeometry(new Polygon([positions]));

        if (this.featureId !== data.id) {
            this.featureId = data.id
            this.drawer.source(Type.RootPolygon).forEachFeature((feature) => {
                this.drawer.source(Type.RootPolygon).removeFeature(feature);
            });
            this.drawer.source(Type.RootPolygon).addFeature(feature);
        }
        var polygon = turf.polygon([positions]);
        var centroid = turf.centroid(polygon);
        this.drawer.map.getView().animate({ // 只设置需要的属性即可
            center: centroid.geometry.coordinates, // 中心点
            duration: 1000, // 缩放持续时间，
            zoom: 11
        })

    }

    async treeSensor(data, e) {
        await this.drawer.draw(Type.Sensor);
        this.drawer.source(Type.Modify).clear();

        const json = { from: "tank", type: "treePoint", code: 0 };
        const feature = this.drawer.source(Type.Sensor).getFeatureById(data.id);
        if (feature === null) {
            json.code = 1;
        } else {
            const sensorType = feature.get("sensorType");
            const text = new Text({
                text: SensorTypeU[sensorType],
                fill: new Fill({ color: "blue" }),
                font: `normal 40px "iconfont"`
            });
            feature.setStyle(new Style({ text: text }));
            const point = feature.getGeometry().getCoordinates();
            this.drawer.map.getView().setCenter(point);
            this.drawer.map.getView().setZoom(9);
        }
        e.source.postMessage(JSON.stringify(json), "*");
    }

    async xyzSensor(data, e) {
        await this.drawer.draw(Type.Sensor);

        const x = this.algo.normalX(data.x);
        const y = this.algo.normalY(data.y);
        const json = { code: 0, from: "tank", type: "xyzPoint" };

        if (data.id === null) {
            const feature = new Feature();
            const text = new Text({
                text: SensorTypeU[data.sensorType],
                fill: new Fill({ color: "blue" }),
                font: `normal 40px "iconfont"`
            });
            feature.set("type", Type.Sensor);
            feature.setStyle(new Style({ text: text }));
            feature.setGeometry(new Point([x, y]));
            this.drawer.source(Type.Modify).clear();
            this.drawer.source(Type.Modify).addFeature(feature);
        } else {
            const feature = this.drawer.source(Type.Sensor).getFeatureById(data.id);
            if (feature === null) {
                json.code = 1;
            } else {
                feature.setGeometry(new Point([x, y]));
            }
        }

        this.drawer.map.getView().setCenter([x, y]);
        this.drawer.map.getView().setZoom(9);

        e.source.postMessage(JSON.stringify(json), "*");
    }

    async cancelSensor(data, e) {
        await this.drawer.draw(Type.Sensor);
        this.drawer.source(Type.Modify).clear();
        const json = { from: "tank", type: "cancelPoint" };
        e.source.postMessage(JSON.stringify(json), "*");
        this.emitter.emit("close-sensor-move");
    }

    async refreshSensor(data, e) {
        this.drawer.source(Type.Modify).clear();
        await this.drawer.draw(Type.Sensor);
        this.emitter.emit("sensor-refresh");
        const json = { from: "tank", type: "refreshPoint" };
        e.source.postMessage(JSON.stringify(json), "*");
    }

    template() { }

    control() {
        const self = this;

        window.onload = function (e) {
            const json = { from: "tank", load: 'true', type: "onload" };
            window.parent.postMessage(JSON.stringify(json), "*");
        }

        window.onmessage = async (e) => {
            const data = JSON.parse(e.data);
            const from = data.from, type = data.clickType
            if (from !== "tank") return;

            // 放开报错
            // this.emitter.emit("socket-close");
            this.emitter.emit("close-sensor-move");
            if (type === "newPoint") {
                await self.createSensor(data, e);
            } else if (type === "selectPoint") {
                await self.selectSensor(data, e);
            } else if (type === "copyPoint") {
                await self.copySensor(data, e);
            } else if (type === "modifyPoint") {
                await self.modifySensor(data, e);
            } else if (type === "treePoint") {
                await self.treeSensor(data, e);
            } else if (type === "xyzPoint") {
                await self.xyzSensor(data, e);
            } else if (type === "cancelPoint") {
                await self.cancelSensor(data, e);
            } else if (type === "refreshPoint") {
                await self.refreshSensor(data, e);
            } else if (type === "rootPoint") {
                await self.rootPointSensor(data, e);
            } else if (type === "rootPolygon") {
                await self.rootPolygonSensor(data, e);
            } else if (type === "faultClick") {
                await self.faultageSensor(data, e);
            } else if (type === "newFaultClick") {
                await self.newFaultage(data, e);
            } else if (type === "refreshFault") {
                await self.refreshFault(data, e);
            } else if (type === "fracturezoneClick") {
                await self.fracturezoneSensor(data, e);
            } else if (type === "newFracturezoneClick") {
                await self.newFracturezone(data, e);
            } else if (type === "refreshFracturezone") {
                await self.refreshFracturezone(data, e);
            } else if (type === "waterenrichedareaClick") {
                await self.waterenrichedareaSensor(data, e);
            } else if (type === "newWaterenrichedareaClick") {
                await self.newWaterenrichedarea(data, e);
            } else if (type === "refreshWaterenrichedarea") {
                await self.refreshWaterenrichedarea(data, e);
            } else if (type === "addLayer") {
                await self.addLayer(data, e);
            } else if (type === "removeLayer") {
                await self.removeLayer(data, e);
            } else if (type === "doubleScreen") {
                await self.doubleScreen(data, e);
            } else if (type === "takeAtaxi") {
                self.emitter.emit("take-a-taxi");
            }
        }
    }
}